﻿using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using System;
using System.Threading.Tasks;
using MimeKit;
using RsCode;

namespace Rswl.Infrastructure
{
    public static class EmailHelper
    {
       
        public static async Task< string> SendAsync( string receiveEmail,string subject,string body )
        {
            var emailOption=AppSettings.GetValue<MailOption>("email");
           
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("发送者", emailOption.Email));//发送人的名称以及邮箱
                message.To.Add(new MailboxAddress("接收者", receiveEmail));//接收人的名称以及邮箱
                message.Subject =subject;//邮件主题
                //html or plain
                var bodyBuilder = new BodyBuilder();
                bodyBuilder.HtmlBody = $"<b>{body}</b>";
                bodyBuilder.TextBody = body;
                message.Body = bodyBuilder.ToMessageBody();
                Multipart multipart = new Multipart("mixed");
                //附件
                //string absolutePath = strfile;
                //MimePart attachment = new MimePart()
                //{
                //    //读取文件，只能用绝对路径
                //    //ContentObject = new ContentObject(File.OpenRead(absolutePath), ContentEncoding.Default),
                //    ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
                //    ContentTransferEncoding = ContentEncoding.Base64,
                //    //文件名字
                //    FileName = strfileName + ".xlsx"
                //};
                //multipart.Add(attachment);
                message.Body = multipart;
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    //smtp服务器，端口，是否开启ssl
                    await client.ConnectAsync(emailOption.Host,emailOption.Port, true);
                    client.Authenticate(emailOption.Email, emailOption.AuthCode);//发送者邮箱以及授权码
                    client.Send(message);
                    client.Disconnect(true);
                }
                return "发送成功";
            }
            catch (Exception ex)
            {
                return "发送失败";       
            }
          
        }
        /// <summary>
        /// 读取指定发件人的邮件
        /// </summary>
        /// <param name="senderEmail"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<string> ReadAsync(string senderEmail)
        {
            //string host= "outlook.office365.com"; int port = 993;
            //string email = "";
            //string authCode = "";
            var emailOption = AppSettings.GetValue<MailOption>("email");
            using (var client = new ImapClient())
            {
                await client.ConnectAsync(emailOption.Host,emailOption.Port, true);
                //await client.ConnectAsync("imap.qq.com", 993, true);
                //登入邮箱
                client.Authenticate(emailOption.Email, emailOption.AuthCode);

                //读取收件箱 Inbox
                //打开邮件文件夹
                client.Inbox.Open(FolderAccess.ReadWrite);
                //读取指定发件者的邮件
                var query = SearchQuery.FromContains(senderEmail);
                var uids = client.Inbox.Search(query);
                if (uids.Count == 0)
                {
                    //读取垃圾邮件
                    //var junkFolder = await client.GetFolderAsync("Junk Email");
                    IMailFolder junkFolder = null;
                    if ((client.Capabilities & (ImapCapabilities.SpecialUse | ImapCapabilities.XList)) != 0)
                    {
                        junkFolder = client.GetFolder(SpecialFolder.Junk);
                    }
                    else
                    {
                        junkFolder = client.GetFolder("Junk");
                    }

                    await junkFolder.OpenAsync(FolderAccess.ReadOnly);
                    //读取指定发件者的邮件
                    query = SearchQuery.FromContains("info@x.com");
                    uids = junkFolder.Search(query);
                    if (uids.Count == 0)
                    {
                        throw new Exception("未找到twitter发送的邮件,垃圾邮件里也没有");
                    }
                    else
                    {
                        //获取第一个邮件
                        var message = await junkFolder.GetMessageAsync(uids[0]);
                        string subject = message.Subject;
                        return subject;
                    }

                }
                else
                {
                    //获取第一个邮件
                    var message = await client.Inbox.GetMessageAsync(uids[0]);
                    string subject = message.Subject;

                    return subject;
                }
                 
            }
        }
    }

    public class MailOption
    {
        /// <summary>
        /// 邮箱服务器地址
        /// </summary>
        public string Host { get; set; }
        /// <summary>
        /// 邮箱端口号
        /// </summary>
        public int Port { get; set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }
        /// <summary>
        /// 邮箱授权码
        /// </summary>
        public string AuthCode { get; set; }
    }
}
